home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2513 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.4 KB

  1. Path: castle.nando.net!news
  2. From: actuary@nando.net   (Bill McCarthy)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Can't figure this out
  5. Date: 22 Jan 1996 03:54:41 GMT
  6. Organization: News & Observer Public Access
  7. Message-ID: <4dv1q1$pbl@castle.nando.net>
  8. References: <31000091.3778302@news.panix.com>
  9. Reply-To: actuary@nando.net (Bill McCarthy)
  10. NNTP-Posting-Host: vyger119.nando.net
  11. X-Newsreader: IBM NewsReader/2 v1.2
  12.  
  13. In <31000091.3778302@news.panix.com>, dm@panix.com (Dan'l) writes:
  14. >I am learning C and I have not had any problems understanding most
  15. >concepts I have learned so far.  But to date I still can't figure out
  16. >how the outcome of this program is 15.  Somehow one of the B's ends up
  17. >a three and the other B a 5, or am I so off base that I can't see
  18. >what's really happening.    Can someone please walk me through this
  19. >one.                                             Thanks     Dan'l
  20. >
  21. >#define A 3
  22. >#define B A + A
  23. >#define C B * B
  24. >
  25. >main()
  26. >{
  27. >    printf("%d", C);
  28. >    return 0;
  29. >}
  30.  
  31. The preprocessor is doing text substitution.  So B will be replaced by
  32. 3 + 3.  And C will be replaced by 3 + 3 * 3 + 3.  That evaluates to
  33. 3 + 9 + 3 which evaluates to 15.
  34.  
  35. The solution is to use parenthesis (a reductant set of parenthesis
  36. may cost a few microseconds of compile time, but there's no cost at
  37. execution time).  Try:
  38.  
  39.     #define  B  ((A) + (A))
  40.     #define  C  ((B) * (B))
  41.  
  42. Bill McCarthy
  43. actuary@nando.net
  44. Wendell, NC  USA
  45.  
  46.